package com.atguigu.tingshu.user.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取声音的上次跳出时间
     * @param userId
     * @param trackId
     * @return
     */
    @Override
    public BigDecimal getTrackBreakSecond(Long trackId, Long userId) {
            //1 获取当前播放的声音秒数（四舍五入）
            Query query = new Query();
            query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(trackId));
            //2 设置每个mongDB单独的集合名称
            String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
            UserListenProcess mongoTemplateOne = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
            //3 数据不为空时，将数据返回
            if (mongoTemplateOne != null) {
                BigDecimal breakSecond = mongoTemplateOne.getBreakSecond();
                return breakSecond.setScale(0, BigDecimal.ROUND_HALF_UP);
            }

        return BigDecimal.ZERO;
    }


    /**
     * 更新播放进度
     * @param userListenProcessVo
     * @param userId
     * @return
     */
    @Override
    public void updateListenProcess(UserListenProcessVo userListenProcessVo, Long userId) {
        //1 从userListenProcessVo中获取数据
        Long trackId = userListenProcessVo.getTrackId();
        BigDecimal breakSecond = userListenProcessVo.getBreakSecond().setScale(0, BigDecimal.ROUND_HALF_UP);
        Long albumId = userListenProcessVo.getAlbumId();
        //2 从MongoDb中查询数据
        //2.1 创建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(trackId));
        //2.2 设置每个mongDB单独的集合名称
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        //2.3 查询数据
        UserListenProcess mongoTemplateOne = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
        //3 判断数据的是否存在
        if (mongoTemplateOne != null){
            //3.1 数据存在，更新数据（通过ID已包含）
            mongoTemplateOne.setBreakSecond(breakSecond);
            mongoTemplateOne.setUpdateTime(new Date());
        }else{
            //3.2 数据不存在，创建数据并保存(没有Id)
            mongoTemplateOne = new UserListenProcess();
            mongoTemplateOne.setUserId(userId);
            mongoTemplateOne.setTrackId(trackId);
            mongoTemplateOne.setBreakSecond(breakSecond);
            mongoTemplateOne.setAlbumId(albumId);
            mongoTemplateOne.setCreateTime(new Date());
            mongoTemplateOne.setUpdateTime(new Date());
        }
        mongoTemplate.save(mongoTemplateOne, collectionName);

        //4 使用MQ对数据库和索引库进行修改
        //4.1 发送到专辑
        TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
        trackStatMqVo.setTrackId(trackId);
        trackStatMqVo.setAlbumId(albumId);
        trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
        trackStatMqVo.setCount(1);
        trackStatMqVo.setBusinessNo(IdUtil.randomUUID());
        //4.1.2 幂等性
        String key = RedisConstant.USER_TRACK_REPEAT_STAT_PREFIX + userId + "_" + albumId + "_" + trackId;
        Long ttl = DateUtil.endOfDay(new Date()).getTime()-System.currentTimeMillis();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", ttl, TimeUnit.MICROSECONDS);
        if (flag)
        rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE,trackStatMqVo);
    }

    /**
     * 获取用户最近播放声音
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String, Long> getLatelyTrack(Long userId) {
        //1.查询当前用户某个声音播放进度
        //1.1 构建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.with(PageRequest.of(0, 1, Sort.Direction.DESC, "updateTime"));
        //1.2 执行查询：注意每个用户都有自己播放进度集合
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
        if (listenProcess != null) {
            Map<String, Long> map = new HashMap<>();
            map.put("albumId", listenProcess.getAlbumId());
            map.put("trackId", listenProcess.getTrackId());
            return map;
        }
        return null;
    }
}
